<template>
   <div ref="chartRef" style=" height: 100%;"></div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import { getOrderTrends } from '@/apis/admin/order'

const chartRef = ref(null)
let chart = null

// 初始化图表
const initChart = async () => {
  await nextTick()
  if (chartRef.value) {
    chart = echarts.init(chartRef.value)
    await setOptions()
  }
}

// 设置图表配置
const setOptions = async () => {
  try {
    const res = await getOrderTrends()
    const orderData = res.data

    // 处理数据格式
    const dates = orderData.map(item => item.date)
    const counts = orderData.map(item => item.count)

    const option = {
    
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        },
        formatter: function(params) {
          const data = params[0]
          return `${data.name}<br/>订单数量：${data.value}`
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: dates,
        axisLine: {
          lineStyle: {
            color: '#999'
          }
        },
        axisLabel: {
          color: '#666',
          rotate: 45
        }
      },
      yAxis: {
        type: 'value',
        axisLine: {
          show: false
        },
        axisLabel: {
          color: '#666'
        },
        splitLine: {
          lineStyle: {
            color: '#eee'
          }
        }
      },
      series: [
        {
          name: '订单数量',
          type: 'line',
          smooth: true,
          data: counts,
          itemStyle: {
            color: '#409EFF'
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: 'rgba(64,158,255,0.3)'
              },
              {
                offset: 1,
                color: 'rgba(64,158,255,0.1)'
              }
            ])
          }
        }
      ]
    }

    chart.setOption(option)
  } catch (error) {
    console.error('获取订单趋势数据失败:', error)
  }
}

// 监听窗口大小变化
const handleResize = () => {
  chart && chart.resize()
}

onMounted(() => {
  initChart()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  if (chart) {
    chart.dispose()
    chart = null
  }
  window.removeEventListener('resize', handleResize)
})
</script>

<style lang="less" scoped>

</style>
